package com.zhdl.common.ytools;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class PublicTools {

    private static ResourceBundle bundle;
    private static final String[] randomValues = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "u",
            "t", "s", "o", "x", "v", "p", "q", "r", "w", "y", "z"};

    /**
     * 函数功能：获得当前的日期
     *
     * @param
     */
    public static String getDateNow() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        return df.format(new Date());
    }

    public static String getShortDateNow() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        return df.format(new Date());
    }

    public static String formatDate(Date dt) {
        if (dt != null) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
            return df.format(dt);
        } else {
            return "";
        }
    }

    public static String getYear() {
        String date1 = getShortDateNow();
        String[] str = date1.split("-");
        return str[0];
    }

    public static String getMonth() {
        String date1 = getShortDateNow();
        String[] str = date1.split("-");
        return str[1];
    }

    public static String gettime() {// 生成详细的时间
        String datestr = "";
        try {
            java.text.DateFormat df = new SimpleDateFormat(
                    "yyyy年MM月dd日 HH点ss分");
            Date date = new Date();
            datestr = df.format(new Date());
        } catch (Exception ex) {

        }

        return datestr;
    }

    public static String ClobToString(Clob clob) {
        String strString = "";
        try {
            Reader is = clob.getCharacterStream();// 得到流
            BufferedReader br = new BufferedReader(is);
            String s = br.readLine();
            StringBuffer sb = new StringBuffer();
            while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
                sb.append(s);
                s = br.readLine();
            }
            strString = sb.toString();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strString;
    }

    // 字符集转换问题
    public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j))
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16)
                    tmp.append("0");
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src, lastPos, pos);
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }

    /**
     * @return ResourceBundle
     * @function getResourceBundle
     */
    private static ResourceBundle getResourceBundle() {
        if (bundle == null)
            //bundle = ResourceBundle.getBundle("init");// 属性文件的文件名
            bundle = ResourceBundle.getBundle("application");// 属性文件的文件名
        return bundle;
    }

    /**
     * 函数功能：获得属性文件的内容
     *
     * @param
     */
    public static String getString(String s) {
        String s1 = null;
        try {
            s1 = getResourceBundle().getString(s);
        } catch (MissingResourceException missingresourceexception) {
            System.out.println("ConfigBundle:getString error!"
                    + missingresourceexception);
        }
        return s1;
    }

    public static String getString(String fileName, String s) {
        String s1 = null;
        try {

            s1 = ResourceBundle.getBundle(fileName).getString(s);

        } catch (MissingResourceException missingresourceexception) {
            System.out.println("ConfigBundle:getString error!"
                    + missingresourceexception);
        }
        return s1;
    }

    public static String getString1(String fileName, String s) {
        String s0 = null;
        String s1 = null;
        try {
            s0 = ResourceBundle.getBundle(fileName).getString("confPath");

            InputStream inStream = new FileInputStream(new File(s0));
            Properties prop = new Properties();
            prop.load(inStream);
            s1 = prop.getProperty(s);
        } catch (MissingResourceException | IOException missingresourceexception) {
            System.out.println("ConfigBundle:getString error!"
                    + missingresourceexception);
        }
        return s1;
    }

    // 根据文件路径删除文件
    public static boolean delfile(String file) {
        boolean b = false;
        File f = new File(file);
        if (f.exists()) {
            b = f.delete();
        }
        return b;
    }

    public static String fileStr(String str) {
        if (str == null) {
            str = "";
        } else {
            str = str.replace("'", "''");
        }

        return str;
    }

    public static String formatnull(String str) {
        if (str != null) {
            return str;
        } else {
            return "";
        }

    }

    public static String getuuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "").toUpperCase();
    }

    public static long Randomlong() {
        Random random = new Random();
        long a = Math.abs((int) (Math.random() * 1000) + 1);
        // System.out.println(a+"****");
        return a;
    }

    //sqlstring预编译的语句 param为预编译？的值(需增加?个数与param[]长度判断,以及最后少个括号)
    public static void showsql(String sqlstring, String[] param) {
        String sql = "";
        //String sqlstring="select * from aa wherw id=? and name=?";
        //截取？
        int i = 0;//当前？的字符位置
        int a = 0;//上次？的字符位置
        for (int j = 0; j < param.length; j++) {

            i = sqlstring.indexOf("?", (i + 1));
            if (j == 0) {
                sql = sqlstring.substring(0, i) + "'" + param[j] + "'";
            } else {

                i = sqlstring.indexOf("?", i);
                sql += sqlstring.substring(a + 1, i) + "'" + param[j] + "'";
            }
            a = i;
        }
        System.out.println(sql);
    }

    public static void showsql(String sqlstring, Object[] param) {
        String sql = "";
        //String sqlstring="select * from aa wherw id=? and name=?";
        //截取？
        int i = 0;//当前？的字符位置
        int a = 0;//上次？的字符位置
        for (int j = 0; j < param.length; j++) {

            i = sqlstring.indexOf("?", (i + 1));
            if (j == 0) {
                sql = sqlstring.substring(0, i) + "'" + param[j].toString() + "'";
            } else {

                i = sqlstring.indexOf("?", i);
                sql += sqlstring.substring(a + 1, i) + "'" + param[j].toString() + "'";
            }
            a = i;
        }
        System.out.println(sql);
    }

    //四舍五入
    public static String numformat(int size, double number) {

        StringBuffer formatString = new StringBuffer("0");
        if (size > 0) {
            formatString.append(".");
        }

        for (int i = 0; i < size; i++) {
            formatString.append("#");
        }

        DecimalFormat df = new DecimalFormat(formatString.toString());
        DecimalFormat dcmFmt = new DecimalFormat("0.00");

        //System.out.println(dcmFmt.format(Float.valueOf(df.format(number))));

        return dcmFmt.format(Float.valueOf(df.format(number)));
    }

    public static String loadURL(String[] params, String[] values) {

        StringBuffer buffer = new StringBuffer();
        try {
            for (int i = 0; i < params.length; i++) {
                if (i == 0) {
                    buffer.append(params[i] + "=");
                    buffer.append(values[i]);
                } else {
                    buffer.append("&" + params[i] + "=");
                    buffer.append(values[i]);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();

    }

    public static String getRandom(int lenght) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < lenght; i++) {
            Double number = Math.random() * (randomValues.length - 1);
            str.append(randomValues[number.intValue()]);
        }

        return str.toString();
    }


/*************************反射相关(2020-3-16)***********************************************************************************************************/
/**
 * 使用org.apache.commons.beanutils进行转换 
 */  
	
 /* public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception{    
		           if(map == null)  
		              return null;  
		     
		          Object obj = beanClass.newInstance();  
		    
		          org.apache.commons.beanutils.BeanUtils.populate(obj, map);  
		    
		          return obj;  
		        }    
		        
	public static Map<?, ?> objectToMap(Object obj){  
		          if(obj == null)  
		              return null;   
		    
		          return new org.apache.commons.beanutils.BeanMap(obj);  
	}    
*/

    /**
     * 使用Introspector进行转换
     */
	 
/*  public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {    
	        if (map == null)   
	            return null;    
	  
	        Object obj = beanClass.newInstance();  
	  
	        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
	        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
	        for (PropertyDescriptor property : propertyDescriptors) {  
	            Method setter = property.getWriteMethod();    
	            if (setter != null) {  
	                setter.invoke(obj, map.get(property.getName()));   
	            }  
	        }  
	  
	        return obj;  
	    }    
	      
	    public static Map<String, Object> objectToMap(Object obj) throws Exception {    
	        if(obj == null)  
	            return null;      
	  
	        Map<String, Object> map = new HashMap<String, Object>();   
	  
	        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
	        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
	        for (PropertyDescriptor property : propertyDescriptors) {    
	            String key = property.getName();    
	            if (key.compareToIgnoreCase("class") == 0) {   
	                continue;  
	            }  
	            Method getter = property.getReadMethod();  
	            Object value = getter!=null ? getter.invoke(obj) : null;  
	            map.put(key, value);  
	        }    
	  
	        return map;  
	    }    
   */

    /**
     * 使用reflect进行转换
     */

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;
    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }

    /***************************************************************************************************************************************/

    public static void main(String[] args) {

        System.out.println(getRandom(8));
        String aa = "9899.0";

        System.out.println("asdfa" + numformat(2, (Double.valueOf(aa))));
        //String return_url="http://tongye.hnta.cn/orderflow/lastflow.ly";

        // System.out.println("asdfa"+java.net.URLEncoder.encode(return_url));
    }
}


